package org.example.trigger.http;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.api.IAuthApi;
import org.example.api.dto.LoginFormDTO;
import org.example.api.dto.LoginResDTO;
import org.example.api.response.Response;
import org.example.domain.auth.service.IAuthService;
import org.example.types.enums.ResponseCode;
import org.example.types.utils.RegexUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import static org.example.types.enums.ResponseCode.SUCCESS;

/**
 * @author yinghuashen
 * @version 1.0
 * @description
 * @date 2025/3/4 16:35
 */

@Slf4j
@RestController
@CrossOrigin("*")
@RequestMapping("/user")
public class UserController implements IAuthApi {

    @Resource
    private IAuthService authService;


    @Override
    @PostMapping("/login")
    public Response<LoginResDTO> login(@RequestBody LoginFormDTO loginForm, HttpSession session) {
        if(loginForm == null || loginForm.getPhone() == null || loginForm.getCode() == null){
            return Response.<LoginResDTO>builder().code(ResponseCode.UN_ERROR.getCode()).info("登录失败").data(null).build();
        }
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            log.info("手机号格式错误");
            // 2.如果不符合，返回错误信息
            return Response.<LoginResDTO>builder().code(ResponseCode.UN_ERROR.getCode()).info("手机号格式错误").data(null).build();
        }
        // 2.校验验证码
        String jwtToken = authService.loginByCode(loginForm.getPhone(), loginForm.getCode());
        if (jwtToken == null || StringUtils.isBlank(jwtToken)) {
            return Response.<LoginResDTO>builder().code(ResponseCode.UN_ERROR.getCode()).info("验证码错误").data(null).build();
        }
        // 3.登录成功，使用JWT生成token，返回token和redis中
        LoginResDTO loginResDTO = new LoginResDTO();
        loginResDTO.setJwtToken(jwtToken);
        return Response.<LoginResDTO>builder().code(SUCCESS.getCode()).info(SUCCESS.getInfo()).data(loginResDTO).build();
    }

    @Override
    @PostMapping("/request_code")
    public Response<Boolean> requestCode(@RequestParam("phone") String phone) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            log.info("手机号格式错误");
            // 2.如果不符合，返回错误信息
            return Response.<Boolean>builder().code(ResponseCode.UN_ERROR.getCode()).info("手机号格式错误").data(false).build();
        }
        boolean codeGenerated = authService.requestCode(phone);
        if (!codeGenerated) {
            return Response.<Boolean>builder().code(ResponseCode.UN_ERROR.getCode()).info("验证码生成失败").data(false).build();
        }
        return Response.<Boolean>builder().code(SUCCESS.getCode()).info(SUCCESS.getInfo()).data(true).build();
    }

}

